﻿
using B.S.GridManage.Api.Write.DTOs;
using B.S.GridManage.ErrorCode;
using Consul;
using System.Net.Http.Json;

namespace B.S.GridManage.Api.Write.TeamService
{
    public class ServiceDiscovery
    {
        private readonly IConsulClient consulClient;
        private readonly HttpClient httpClient;

        /// <summary>
        /// 俩客户端,一个是consul客户端(找服务的实例),另一个是http客户端(请求数据的)
        /// </summary>
        /// <param name="consulClient"></param>
        /// <param name="factory"></param>
        public ServiceDiscovery(IConsulClient consulClient,IHttpClientFactory factory)
        {
            this.consulClient = consulClient;
            this.httpClient = factory.CreateClient();//通过factrory工厂生产的
        }
        /// <summary>
        /// 根据服务名字取实例地址
        /// </summary>
        /// <param name="serviceName">服务名字</param>
        /// <returns></returns>
        public async Task<string>  GetUrlAsync(string serviceName) {
            var service = await consulClient.Health.Service(serviceName);//根据服务名找到服务
            var lenth = service.Response.Length; //服务里实例的个数
            var index = new Random().Next(0,lenth-1);//在0和个数之间生成一个随机数
            var instance = service.Response[index];//根据随机数取一个实例

            return $"http://{instance.Service.Address}:{instance.Service.Port}";
        }


        public async Task<ApiResult<List<GridTeamDto>>> GetDataFromReadAsync(string url,string api) {
            Uri uri = new Uri(url+api);
            var res = await  httpClient.GetAsync(uri);
            res.EnsureSuccessStatusCode();//200

            return await res.Content.ReadFromJsonAsync<ApiResult<List<GridTeamDto>>>();
        }
    }
}
